package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;
    /**
     * 自媒体文章自动审核
     * @param id 自媒体文章id
     */
    @Async //标明是一个异步调用的方法
//    @GlobalTransactional
    @Override
    public void autoScanWmNews(Integer id) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //1.获取文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(wmNews == null){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }

        //文章状态为1的时候，才会审核
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //获取文本和图片（内容的图片+封面的图片）
            Map<String,Object> textAndImage = handleTextAndImages(wmNews);

            //自管理敏感词审核
            boolean isSensitive = handleSensitive((String) textAndImage.get("content"),wmNews);
            if(!isSensitive) return;

            //2.审核纯文本内容
            boolean isTextScan = handleTextScan((String) textAndImage.get("content"),wmNews);
            if(!isTextScan)return;

            //3.审核图片
            boolean isImageScan = handleImageScan((List<String>) textAndImage.get("images"),wmNews);
            if(!isImageScan)return;


            //4.审核成功，保存app端相关的文章，状态改为9,回填article_id
            ResponseResult responseResult = saveAppArticle(wmNews);
            if(!responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-保存app端文章失败");
            }

//            int a = 1/0;

            //回填article_id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,WmNews.Status.PUBLISHED.getCode(), "审核成功");

        }

    }

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    /**
     * 自管理敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        //初始化敏感词库  select 敏感词 from wm_sensitive
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        SensitiveWordUtil.initMap(sensitiveList);

        //匹配内容中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(map.size() > 0){
            flag = false;
            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(), "文章中包含了敏感词："+map);
        }
        return flag;
    }

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 审核成功，保存app端相关的文章
     * @param wmNews
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();

        //属性拷贝
        BeanUtils.copyProperties(wmNews,dto);

        //布局
        dto.setLayout(wmNews.getType());

        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorId(wmUser.getId().longValue());
            dto.setAuthorName(wmUser.getName());
        }

        //article_id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }

        //创建时间
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = articleClient.saveAppArticle(dto);
        return responseResult;
    }

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 图片审核
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {

        boolean flag = true;


        if(images == null || images.size() == 0){
            return flag;
        }

        List<byte[]> imageList = new ArrayList<>();

        //去重
        images = images.stream().distinct().collect(Collectors.toList());

        try {
            for (String image : images) {
                //下载图片
                byte[] bytes = fileStorageService.downLoadFile(image);

                //识别图片中的文字，进行自管理敏感词审核
                InputStream in = new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(in);
                String resultStr = tess4jClient.doOCR(bufferedImage);
                //自管理敏感词审核
                boolean isSensitive = handleSensitive(resultStr, wmNews);
                if(!isSensitive){
                    return isSensitive;
                }

                imageList.add(bytes);
            }
            Map map = greenImageScan.imageScan(imageList);
            if(map != null){
                //失败
                if(map.get("suggestion").equals("block")){
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章的图片中存在敏感内容");
                    flag = false;
                }
                //人工审核，不确定
                if(map.get("suggestion").equals("review")){
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章的图片中存在不确定内容");
                    flag = false;
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 审核纯文本内容
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {

        boolean flag = true;

        try {
            Map map = greenTextScan.greeTextScan(content + "-" + wmNews.getTitle());
            if(map != null){
                //失败
                if(map.get("suggestion").equals("block")){
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章中存在敏感内容");
                    flag = false;
                }
                //人工审核，不确定
                if(map.get("suggestion").equals("review")){
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章中存在不确定内容");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 修改自媒体文章
     * @param wmNews
     * @param status
     * @param reason
     */
    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 获取文本和图片（内容的图片+封面的图片）
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {

        //存入纯文本内容
        StringBuilder stringBuilder = new StringBuilder();

        //存入图片列表
        List<String> images = new ArrayList<>();


        //1.从内容中获取图片和纯文本
        List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
        for (Map map : maps) {
            //纯文本
            if(map.get("type").equals("text")){
                stringBuilder.append(map.get("value"));
            }
            //图片
            if(map.get("type").equals("image")){
                images.add((String) map.get("value"));
            }
        }

        //2.从封面中获取图片
        if(StringUtils.isNotBlank(wmNews.getImages())){
            images.addAll(Arrays.asList(wmNews.getImages().split(",")));
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",images);
        return resultMap;
    }
}
